package org.dyk.seamanshousefrontdesk.controller;

import org.dyk.seamanshousefrontdesk.model.User;
import org.dyk.seamanshousefrontdesk.service.user.UserService;
import org.dyk.seamanshousefrontdesk.tools.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = {"/user"})
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户主页
     * @param session
     * @return
     */
    @RequestMapping("")
    public String userHome(HttpSession session, Model model){
        //获取用户信息
        User userData = (User) session.getAttribute(Constants.USER_SESSION);
        model.addAttribute("userData",userData);
        return "userHome";
    }

    /**
     * 用户修改 验证
     * @param userLoginName
     * @param userPassword
     * @param userName
     * @param session
     * @return
     */
    @RequestMapping(value = {"/updataUser"}, method = RequestMethod.POST)
    @ResponseBody
    public boolean updataUser(@RequestParam String userLoginName,
                              @RequestParam String userPassword,
                              @RequestParam String userName,
                              HttpSession session){
        User userData = (User)session.getAttribute(Constants.USER_SESSION);
        User user = userService.updataUser(userData.getUid(), userLoginName, userPassword, userName);
        if (null != user){
            //修改成功，覆盖用户session
            session.setAttribute(Constants.USER_SESSION,user);
            return true;
        }else {
            return false;
        }
    }

    /**
     * 用户上传头像
     * @param userImg
     * @param session
     * @return
     */
    @RequestMapping(value = {"/updataHead"}, method = RequestMethod.POST)
    @ResponseBody
    public boolean updataUser(@RequestPart MultipartFile userImg, HttpSession session){
        User userData = (User)session.getAttribute(Constants.USER_SESSION);
        User user = userService.updataHead(userData.getUid(), userImg);
        if (null != user){
            //修改成功，覆盖用户session
            session.setAttribute(Constants.USER_SESSION,user);
            return true;
        }else {
            return false;
        }
    }

    /**
     * 用户退出
     * @param session
     * @return
     */
    @RequestMapping(value = {"/loginOut"})
    @ResponseBody
    public boolean loginOut(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);
        return true;
    }
}
